package com.baseframe.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baseframe.auth.utils.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;


/**
 * 自动填充
 */

@Slf4j
public class BaseMetaObjectHandler implements MetaObjectHandler {

    //
    @Override
    public void insertFill(MetaObject metaObject) {




        String tableName = getTableName(metaObject);


        log.info("insert自动填充:{}",tableName);

        if (AuthUtil.getUserBean()!=null){
            this.strictInsertFill(metaObject,"createBy", AuthUtil::getUserId,Long.class);
            this.strictInsertFill(metaObject,"updateBy",AuthUtil::getUserId,Long.class);
        }

        this.strictInsertFill(metaObject,"createTime",Date::new, Date.class);
        this.strictInsertFill(metaObject,"updateTime",Date::new, Date.class);


    }

    /**
     * 自动填充
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("update自动填充:{}",getTableName(metaObject));

        if (AuthUtil.getUserBean()!=null){
            this.strictUpdateFill(metaObject,"updateBy",AuthUtil::getUserId,Long.class);
        }

        this.strictUpdateFill(metaObject,"updateTime",Date::new, Date.class);



    }

    private String getTableName(MetaObject metaObject){
        TableInfo tableInfo = findTableInfo(metaObject);

        return tableInfo.getTableName();
    }
}
